package com.dding.cms.base.service.impl;

import static com.dding.cms.base.web.util.Utils.formatPath;

import java.awt.Color;
import java.io.File;

import org.dding.core.util.StringUtils;

import com.dding.cms.base.service.ImageService;
import com.dding.cms.base.web.bo.MarkConfigBO;
import com.dding.cms.base.web.util.ImageCut;
import com.dding.cms.common.image.ImageScale;
import com.dding.cms.common.image.ImageScaleImpl;

public class ImageServiceImpl implements ImageService {

	private ImageScale imageScale = new ImageScaleImpl();

	@Override
	public File mark(File tempFile, MarkConfigBO conf, String webPath)
			throws Throwable {
		boolean imgMark = !StringUtils.isBlank(conf.getMark_image());
		if (imgMark) {
			File markImg = formatPath(webPath, conf.getMark_image());
			imageScale.imageMark(tempFile, tempFile, conf.getMark_width(),
					conf.getMark_height(), conf.getMark_position(),
					conf.getMark_offset_x(), conf.getMark_offset_y(), markImg);
		} else {
			imageScale.imageMark(tempFile, tempFile, conf.getMark_width(),
					conf.getMark_height(), conf.getMark_position(),
					conf.getMark_offset_x(), conf.getMark_offset_y(),
					conf.getMark_content(), Color.decode(conf.getMark_color()),
					conf.getMark_size(), conf.getMark_alpha());
		}
		return tempFile;
	}

	@Override
	public void resizeFixImg(ImageCut imageCut) throws Exception {

		File file = formatPath(imageCut.getWebPath(), imageCut.getImgSrcPath());
		imageScale.resizeFix(file, file, imageCut.getReMinWidth(),
				imageCut.getReMinHeight(),
				getLen(imageCut.getImgTop(), imageCut.getImgScale()),
				getLen(imageCut.getImgLeft(), imageCut.getImgScale()),
				getLen(imageCut.getImgWidth(), imageCut.getImgScale()),
				getLen(imageCut.getImgHeight(), imageCut.getImgScale()));

	}

	private int getLen(int len, float imgScale) {
		return Math.round(len / imgScale);
	}

	@Override
	public void resizeFixImg(String webPath, String imgSrcPath, int boxWidth,
			int boxHeight) throws Exception {

		File file = formatPath(webPath, imgSrcPath);
		imageScale.resizeFix(file, file, boxWidth, boxHeight);
	}

}
